//
//  IGBaseRequest.m
//  jingdongfang
//
//  Created by BOE on 2017/8/9.
//  Copyright © 2017年 ZhiYu Hao. All rights reserved.
//

#import "IGBaseRequest.h"
#import "NSString+Extension.h"
#import "IGBaseRequest+IGTokenInvalidMethod.h"
#import "IGBaseResp.h"
#import "LJSystemInfoUtils.h"
#import "IGRequestHUB.h"

@interface IGBaseRequest()

//@property (nonatomic, strong) Class decodeClass;
//@property (nonatomic, assign) IGApiResultStatus resultStatus;

@end

@implementation IGBaseRequest

- (void)startWithDecodeClass:(Class)decodeClass CompletionBlockWithSuccess:(IGRequestCompletionBlock)completion {
    
    if ([self isNeedHub]) {
        [self addAccessory:[IGRequestHUB shareIGRequestHUB]];
    }
    
    self.resultStatus = IGApiResultStatusStart;
    self.decodeClass = decodeClass;
    [self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLogDebug(@"===SUCCESS请求的参数===:%@",request);
        NSLogDebug(@"===SUCCESS返回的数据===:%@", request.responseObject);
        
        //数据解析
       [self parseResponseObject:request.responseJSONObject
                           error:nil
                   completeBlock:completion];
        
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLogDebug(@"===ERROR请求的参数===:%@",request);
        NSLogDebug(@"===ERROR返回的数据===:%@", request.responseObject);
        NSLogDebug(@"===ERROR信息===:%@", request.error);

        //业务逻辑判断
        [self parseResponseObject:request.responseJSONObject
                            error:request.error
                    completeBlock:completion];
    }];
}

- (void)parseResponseObject:(id)responseObject
                      error:(NSError *)error
              completeBlock:(IGRequestCompletionBlock)completion
{
    // request is timeout or server error occured.
    if (error) {
        self.resultStatus = IGApiResultStatusServerErr;
        [self operationWithResponseObject:nil
                                    error:error
                            completeBlock:completion];
        return;
    }
    
    // decodeClass is not exists, return json data directly.
    Class decodeClass = [self decodeClass];
    if (!decodeClass || ![decodeClass isSubclassOfClass:[JSONModel class]]) {
        NSError *respError = [NSError errorWithDomain:@"Model Exception" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"decodeClass is not model"}];
        self.resultStatus = IGApiResultStatusIOSException;
        [self operationWithResponseObject:nil
                                    error:respError
                            completeBlock:completion];
        
        return;
    }
    
    NSError *respError = nil;
    IGBaseResp *resp = nil;
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        resp = [[decodeClass alloc] initWithDictionary:responseObject error:&respError];
    } else if ([responseObject isKindOfClass:[NSData class]]) {
        resp = [[decodeClass alloc] initWithData:responseObject error:&respError];
    } else if ([responseObject isKindOfClass:[NSString class]]) {
        resp = [[decodeClass alloc] initWithString:responseObject error:&respError];
    }
    // parse format error.
    if (respError || !resp) {
        NSError *respError = [NSError errorWithDomain:@"Model Exception" code:-2 userInfo:@{NSLocalizedDescriptionKey: @"class decode exception"}];
        self.resultStatus = IGApiResultStatusIOSException;
        [self operationWithResponseObject:nil
                                    error:respError
                            completeBlock:completion];
        return;
    }

    // business logic error.
    if (![resp.resHeader.code isEqualToString:@"success"]) {
        self.resultStatus = IGApiResultStatusLogicErr;
        [self operationWithResponseObject:resp
                                    error:nil
                            completeBlock:completion];
        return;
    }
    
    self.resultStatus = IGApiResultStatusSuccess;
    completion(resp, nil);
}

- (BOOL)showLogicErrorToast {
    return YES;
}

- (BOOL)isNeedHub {
    return NO;
}

- (BOOL)isHttps {
    return NO;
}

- (NSString *)baseUrl {
    if (![self isHttps]) {
        return [[IGServerConfig sharedConfig] httpApiBaseUrl];
    } else {
        return [[IGServerConfig sharedConfig] httpsApiBaseUrl];
    }
}

- (YTKRequestMethod)requestMethod {
    return YTKRequestMethodPOST;
}

///>接口请求超时时间
- (NSTimeInterval)requestTimeoutInterval {
    return 15;
}

- (long long)cacheVersion {
    return [IGServerConfig sharedConfig].cacheVersion;
}

///>所有请求统一的HeaderField
- (NSDictionary<NSString *,NSString *> *)requestHeaderFieldValueDictionary {

    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:KLanguage];
    BOOL isChinese = NO;
    if ([language containsString:@"zh-Hans"]) {
        isChinese = YES;
    } else isChinese = NO;
    
    NSString *deviceVersion = [LJSystemInfoUtils deviceVersion];
    NSString *sysVersion = [[UIDevice currentDevice] systemVersion];
    return @{
             @"locale":isChinese?@"zh-CN":@"en-US",
             @"appVersion": [IGServerConfig sharedConfig].appVersion, ///> 客户端版本
             @"osType": @"ios",                                       ///> 平台类型，ios
             @"uId": [IGUser getUid],
//             @"uId": @"6405",
             @"uToken": [IGUser getuToken],
             @"Content-Type": @"application/x-www-form-urlencoded; charset=utf-8",
             @"deviceVersion":deviceVersion,
             @"sysVersion":sysVersion
             };
}

- (NSString *)arrToJsonString:(NSArray *)arr {
    NSString *arrStr = [arr componentsJoinedByString:@","];
    return [NSString stringWithFormat:@"%@", arrStr];
}

@end
